package com.pashanhoo.Thread.pool;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 胡庆安
 * @version V1.0
 * @Package com.pashanhoo.Thread.pool
 * @date 2020/10/23 16:43
 * @Copyright © 2010-2020 爬山虎科技（扬州）股份有限公司
 */
public class WaitNacos {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Condition condition2 = lock.newCondition();

        TimeUnit timeUnit = TimeUnit.SECONDS;
        long timeOut = 1000;

        Thread thread =  new Thread(()->{
            while (true) {
                long nanos = timeUnit.toNanos(timeOut);
                lock.lock();
                try {
                    if (nanos <= 0) {
                        break;
                    }
                    nanos = condition.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        },"t1");
        thread.start();
        Thread.sleep(1000);
        Thread thread2 = new Thread(()->{
            while (true) {
                long nanos = timeUnit.toNanos(timeOut);
                lock.lock();
                try {
                    if (nanos <= 0) {
                        break;
                    }

                    nanos = condition2.awaitNanos(nanos);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }

        },"t2");


        thread2.start();

    }
}

